//
//  WBComposeController.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/21.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
import SVProgressHUD


private let baseTag = 10000
//定义枚举
enum HMComposeType: Int {
    case Picture = 10000
    case AtSome
    case Topic
    case Emoticon
    case More
}

class WBComposeController: UIViewController {
    
    //按钮的监听事件
    @objc internal func toolBarButtonDidClick(btn: UIButton) {
        //通过原始值获取枚举对象  不能够判断可选类型的枚举值
        let enumType = HMComposeType.init(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            selector.userWillChosePic(cell: nil)
            
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emoticon:
                        //设置input 完成键盘的切换
            textView.inputView = (textView.inputView == nil ? keyboardView : nil)
            if !textView.isFirstResponder {
                
                textView.becomeFirstResponder()
            }

            //刷新输入视图
            textView.reloadInputViews()
        case .More:
            print("更多")
        }
    }

    @objc internal func close() {
        dismiss(animated: true, completion: nil)
    }
    @objc private func sendBtnDidClick() {
        
        //发布微博
        //遍历文本带属性
        var strM = String()
        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: [], using: { (dict,range,_) -> () in
            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
                //图片
                strM += attachment.chs ?? ""
            } else {
                //文字或者emoji
                let sub = (self.textView.text as NSString).substring(with: range)
                strM += sub
            }
        })

        
        //====================================
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        //post请求不需要作urlEncode，get需要
        let parameters = ["access_token": WBUserAccountViewModel.shared.userAccount?.access_token,
                          "status": textView.imageEmoticon2Chs()]
        //正在加载提示
        SVProgressHUD.show()
        if selector.selectedImages.count == 0 {
            
            ZQWNetworkTools.shared.request(method: .POST, UrlSting: urlString, parameter: parameters, finished: {(responseObject,error) -> () in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    return
                }
                self.dismiss(animated: true, completion: {
                    
                    SVProgressHUD.showSuccess(withStatus: "发布成功")
                    
                })
            })
            
        }else{//上传
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"

            //图片微博,多张图上传
            ZQWNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                
                for image in self.selector.selectedImages {
                    //获取图片的二进制数据
                    let imageData = UIImagePNGRepresentation(image)
                    formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "\(Date())", mimeType:  "application/octet-stream"
                )}
                
                
            }, progress: nil, success: { (_, result) in
                self.dismiss(animated: true, completion: {
                    
                SVProgressHUD.showSuccess(withStatus: "发布成功")
                    
                })
            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发布失败")
            })

        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        setNavBar()
        setTextView()
        setToolBar()
        setSelectorPicture()
        //将toolbar移到最顶层
        self.view.bringSubview(toFront: toolBar)
        //调用通知
        registerNotification()
    }
    
    //放视图将要显示的时候 就应该判断是否显示图片选择器
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        selector.view.isHidden = selector.selectedImages.count == 0
    }
    //注册通知
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmoticon(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
}
    func insertEmoticon(n: Notification) {
        print(n)
        guard let em = n.object as? HMEmoticon else {
            //点击的就是删除,执行回删
            textView.deleteBackward()
            return
  }
        //如果点击的是emoji表情
        if em.type == 1{
            //将emoji表情添加到对应的文本中
            textView.replace(textView.selectedTextRange!, withText: em.emojiStr ?? "")
            return
  }
        //处理图片表情
        textView.inputEmoticon(em: em)
        //程序走到这里一定有表情图片将图片包装到福建对象中 attachment
        //通过附件对象实力化属性字符串
        let attachment = HMTextAttachment()
        attachment.chs = em.chs
        let linHeight = textView.font!.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: linHeight, height: linHeight)
        attachment.image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
        //后面需要给它添加属性 imageText
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        //需要给福建属性文本添加属性
        imageText.addAttributes([NSFontAttributeName: textView.font!], range: NSRange(location: 0, length: 1))
        //获取当前文本输入视图可辨的属性字符串 strM
        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
        //在替换属性文本之前先记录光标选中的位置
        let range = textView.selectedRange
        //将imageText替换到strM对应的光标位置
        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
        //将strM赋值给textView.attributedText
        textView.attributedText = strM
        //将光标恢复到之前选中的位置
        textView.selectedRange = NSRange(location: range.location+1, length: 0)
        //输入图片等时候无法调用代理方法，需要手动调用
        
        textView.delegate?.textViewDidChange?(textView)
}
    
    
    
    
    
    //监听通知的变化
    func keyboardChanged(n: NSNotification){
        print(n)
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        //让底部toolBar能过移动
        //修改底部的约束
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        //跟新约束
        UIView.animate(withDuration: 0.25, animations: {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
                //动画时间失效   不能写在更新约束内部self.view.layoutIfNeeded()
            })
            //强制刷新页面
            self.view.layoutIfNeeded()
        })
        
    }
    //懒加载底部工具条
    lazy var toolBar: UIStackView = {
        let bottomBar = UIStackView(frame: CGRect.zero)
        //初始设置
        //设置方向
        bottomBar.axis = .horizontal
        //设置填充的的方式
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
    
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.lightGray, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        
        return barButtonItem
    }()

    lazy var textView: HMEmoticonTextView = {
        let tv = HMEmoticonTextView()
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        //textView没有展位文本
        tv.delegate = self
        //键盘的拖拽
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
                
        return tv
        
    }()
    
    lazy var placeHolderLabel: UILabel = {
        let l = UILabel(title: "牛逼的人生不需要带盐", textCololr: UIColor.lightGray, fontSize: 18)
        return l
    }()
    
    lazy var selector: WBPicCollectionViewController = {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: selectorCellWidth, height: selectorCellWidth)
        //设置行和列的最小间距
        flowLayout.minimumLineSpacing = selectorMargin
        flowLayout.minimumInteritemSpacing = selectorMargin
        //设置组的内边距
        flowLayout.sectionInset = UIEdgeInsets(top: selectorMargin, left: selectorMargin, bottom: 0, right: selectorMargin)
        let picSel = WBPicCollectionViewController(collectionViewLayout: flowLayout)
        picSel.collectionView?.backgroundColor = UIColor.blue
        return picSel
    }()
    //自定义键盘视图
    lazy var keyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
}
    extension WBComposeController: UITextViewDelegate {
        func textViewDidChange(_ textView: UITextView) {
            //判断发布微博按钮的状态
            sendBtn.isEnabled = textView.hasText
            
            //占位文本需要隐藏
            placeHolderLabel.isHidden = textView.hasText
        }
    }
    //MARK: UI界面
    extension WBComposeController {
        //非常重要＊＊＊＊ 添加子视图控制器
        func setSelectorPicture() {
            self.addChildViewController(self.selector)
            self.view.addSubview(selector.view)
            //设置约束
            selector.view.snp.makeConstraints { (make) in
                make.bottom.left.right.equalTo(self.view)
                //设置高度
                make.height.equalTo(ScreenHeight / 3 * 2)
            }

            
            
            
            
        }
        
        
        func setToolBar() {
            self.view.addSubview(toolBar)
            //设置约束'
            toolBar.snp.makeConstraints { (make) in
                make.left.right.bottom.equalTo(self.view)
                make.height.equalTo(40)
            }
            toolBar.backgroundColor = UIColor.red
            
            //添加按钮
            let imageNames = ["compose_toolbar_picture",
                              "compose_mentionbutton_background",
                              "compose_trendbutton_background",
                              "compose_emoticonbutton_background",
                              "compose_add_background"]
            for (index,imageName) in imageNames.enumerated() {
                let btn = UIButton()
                
                btn.setImage(UIImage(named:imageName), for: .normal)
                btn.backgroundColor = UIColor(white: 0.96, alpha: 1)
                //自适应大小
                btn.sizeToFit()
                //添加到toolBar
                toolBar.addArrangedSubview(btn)
                //监听按钮的点击事件
                btn.addTarget(self, action: #selector(toolBarButtonDidClick(btn:)), for: .touchUpInside)
                //设置tag值
                btn.tag = index + baseTag
            }
            
        }

        //设置textView
        func setTextView() {
            //添加子视图
            self.view.addSubview(textView)
            //添加占位文本
            self.textView.addSubview(placeHolderLabel)
            
            //实例化textView控件 添加约束
            textView.snp.makeConstraints { (make) in
                make.top.left.right.equalTo(self.view)
                //添加高度约束
                make.height.equalTo(ScreenHeight / 3)
            }
            
            placeHolderLabel.snp.makeConstraints { (make) in
                make.top.equalTo(textView).offset(8)
                make.left.equalTo(textView).offset(5)
            }
            
            //设置占位文本的约束
        }

      func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "返回上一页", target: self, action: #selector(close))
        
        //设置发布按钮
        self.navigationItem.rightBarButtonItem = sendBtn
        //设置导航条文字 属性文本
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        if let userName = WBUserAccountViewModel.shared.userAccount?.name{
            
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //修改属性文本的属性 使用可变的属性文本
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName: UIColor.darkGray], range: range)
            //给label的属性文本赋值
            titleLabel.attributedText = strM
        }else{
            titleLabel.text = "发布微博"
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
        
    
    }
            
        

